//
//  ViewController.m
//  MobileChecker
//
//  Created by Lymons on 15-1-4.
//  Copyright (c) 2015年 Lymons. All rights reserved.
//

#import "ViewController.h"
#import "AuthLoginViewModel.h"
#import "AutoCheckService.h"
#import "AppDelegate.h"
#import "ResultSendCompletedViewController.h"
#import "DiagnosisListViewController.h"
#import "SystemUtils.h"

@interface ViewController ()

@property (strong, nonatomic) IBOutlet UIButton* loginButton;
@property (strong, nonatomic) IBOutlet UITextField *authCode;
@property (weak, nonatomic) IBOutlet UILabel *descriptionText;
@property (weak, nonatomic) IBOutlet UILabel *codeName;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *loadingIndicator;
@property (strong, nonatomic) AuthLoginViewModel *viewModel;
@property (strong, nonatomic) AutoCheckService *gpsService;

@property (nonatomic, strong) UIImageView *splashView;
@property (strong, nonatomic) IBOutlet UILabel *versionLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (self.sendingResult) {
        self.navigationItem.title = @"サーバ送信";
        self.descriptionText.text = @"店舗コードを入力してください。";
        self.codeName.text = @"店舗コード";
        [self.authCode becomeFirstResponder];
    } else {
//        [self splashShow];
    }

    if (BELOWIOS7) {
        [self.loginButton setBackgroundColor:[UIColor clearColor]];
    }
    self.gpsService = [[AutoCheckService alloc] init];
    
    NSString *File = [[NSBundle mainBundle] pathForResource:@"Info" ofType:@"plist"];
    NSMutableDictionary* dict = [[NSMutableDictionary alloc] initWithContentsOfFile:File];
    self.versionLabel.text = [NSString stringWithFormat:@"%@%@", @"Ver: ", [dict objectForKey:@"App version"]];
    
    [self bindViewModel];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.gpsService stopGps];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)bindViewModel {
    self.viewModel = [[AuthLoginViewModel alloc] init];
    RAC(self.viewModel, authCode) = self.authCode.rac_textSignal;
    
    if (self.sendingResult) {
        self.loginButton.rac_command = self.viewModel.executeSend;
    } else {
        self.loginButton.rac_command = self.viewModel.executeAuth;
    }
    
    AppDelegate *delegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [delegate.indicatorDispose dispose];
    @weakify(self);
    delegate.indicatorDispose = [self.loginButton.rac_command.executing subscribeNext:^(NSNumber *x) {
        @strongify(self);
        BOOL executing = [x boolValue];
        [UIApplication sharedApplication].networkActivityIndicatorVisible = executing;
        self.loadingIndicator.hidden = !executing;
        self.authCode.enabled = !executing;
        if (executing) {
            [self.loadingIndicator startAnimating];
            self.authCode.textColor = [UIColor grayColor];
        } else {
            [self.loadingIndicator stopAnimating];
            self.authCode.textColor = [UIColor blackColor];
        }
    }];
    
    [self.loginButton.rac_command.executionSignals
     subscribeNext:^(id x) {
         @strongify(self);
         [self.authCode resignFirstResponder];
     }];
    
    [self.viewModel.connectionErrors subscribeNext:^(NSError *error) {
        @strongify(self);
//        self.viewModel.apiSucceed = YES; // for debug
        if (self.viewModel.apiSucceed) {
            return ;
        }
        NSError *err = nil;
        NSString *errMsg = nil;
        NSData *jsonData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
        if (jsonData) {
            NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                       options:NSJSONReadingAllowFragments
                                                                         error:&err];
            
            DDLog(@"%@", jsonObject);
            errMsg = jsonObject[@"error"];
        } else {
            errMsg = error.userInfo[NSLocalizedDescriptionKey];
        }
        
        if (errMsg == nil) {
            errMsg = @"サーバー通信に失敗しました";
        }
        UIAlertView *alert =
        [[UIAlertView alloc] initWithTitle:@"Error"
                                   message:errMsg
                                  delegate:nil
                         cancelButtonTitle:@"OK"
                         otherButtonTitles:nil];
        [alert show];
    }];
    
    [RACObserve(self, viewModel.apiSucceed) subscribeNext:^(NSNumber *x) {
        @strongify(self);
        if ([x boolValue]) {
            self.sendingResult ? [self performSegueWithIdentifier:@"SendCompleted" sender:self] : [self performSegueWithIdentifier:@"AuthCompleted" sender:self];
        }
    }];
    
}

#pragma mark -

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"SendCompleted"]) {
        if ([segue.destinationViewController isKindOfClass:[ResultSendCompletedViewController class]]) {
            ResultSendCompletedViewController *vc = (ResultSendCompletedViewController *)segue.destinationViewController;
            vc.shopCodeString = self.viewModel.authCode;
            vc.checkNumberString = self.viewModel.assessmentNoString;
            vc.successString = self.viewModel.successMessageString;
            if (vc.checkNumberString == nil) {
                vc.checkNumberString = @"54321"; // for debug
            }
        }
    } else if ([segue.identifier isEqualToString:@"AuthCompleted"]) {
        if ([segue.destinationViewController isKindOfClass:[DiagnosisListViewController class]]) {
            DiagnosisListViewController *vc = (DiagnosisListViewController *)segue.destinationViewController;
            vc.needToCheckFromBegining = YES;
        }
    }
}

#pragma mark -

- (void)splashShow
{
    _splashView = [[UIImageView alloc] initWithFrame:self.navigationController.view.bounds];
    _splashView.image = [UIImage imageNamed:@"LaunchImage"];
    [self.navigationController.view addSubview:_splashView];
    [self.navigationController.view bringSubviewToFront:_splashView];
    [self performSelector:@selector(splashDone) withObject:nil afterDelay:5];
    
    //Create and add the Activity Indicator to splashView
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    activityIndicator.tag = 1001;
    activityIndicator.alpha = 1.0;
    activityIndicator.center = CGPointMake(_splashView.center.x, _splashView.center.y-50);
    activityIndicator.hidesWhenStopped = NO;
    [_splashView addSubview:activityIndicator];
    [activityIndicator startAnimating];
    
    UILabel *version = [[UILabel alloc] initWithFrame:CGRectZero];
    version.text = @"Ver 1.0.1";
    version.textColor = [UIColor lightGrayColor];
    version.font = [UIFont systemFontOfSize:18];
    version.backgroundColor = [UIColor clearColor];
    [version sizeToFit];
    version.center = _splashView.center;
    [_splashView addSubview:version];
}

- (void)splashDone
{
    [[_splashView viewWithTag:1001] setHidden:YES];
    [_splashView removeFromSuperview];
    [self.authCode becomeFirstResponder];
}

@end
